package com.v1.web.action;

import static com.v1.util.Constant.USER;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import weibo4j.model.User;
import weibo4j.model.WeiboException;

import com.v1.weibo4j.Weibo4jConfigAgent;
import com.v1.weibo4j.Weibo4jLO;

public class LoginAction extends DefaultAction {

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return mapping.findForward("login");
	}

	public ActionForward forward(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Weibo4jConfigAgent agent = (Weibo4jConfigAgent) getBean("Weibo4jConfigAgent");
		ActionForward authorize = agent.getAuthorize();
		String nexturl = getString(request, NEXTURL);
		setAttributeToSession(request, NEXTURL, nexturl);
		return authorize;
	}

	public ActionForward authorize(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String code = getString(request, "code");
		log.debug("code: " + code);

		Weibo4jLO agent = (Weibo4jLO) getBean("Weibo4jLO");
		try {
			agent.authorize(code);
		} catch (Exception e) {

			if (e instanceof WeiboException) {
				if (((WeiboException) e).getStatusCode() == 21315) {
					log.debug("Token expired");
					logout(mapping, form, request, response);
					return forward(mapping, form, request, response);
				}

			}
		}

		User user = agent.getUser();
		setAttributeToSession(request, USER, user);

		String nexturl = (String) getAttributeFromSession(request, NEXTURL);
		log.debug("nexturl: " + nexturl);
		if (StringUtils.isEmpty(nexturl)) {
			nexturl = "index.html";
		}
		ActionForward redirct = new ActionForward("", nexturl, true, "");
		return redirct;
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		session.invalidate();
		Weibo4jLO agent = (Weibo4jLO) getBean("Weibo4jLO");
		agent.destroy();
		return INDEX;
	}

}